/*
 * File Name:               XAsyncHelper.cs
 * 
 * Description:             普通类
 * Author:                  lisiyu
 * Create Date:             2016/06/28
 */

using System;
using System.Collections.Generic;
using System.Threading;

public class XAsyncHelper : SingletonTemplate<XAsyncHelper>
{
    private Thread mThread;
    private Queue<Action> mAsyncHandlers = new Queue<Action>();
    private Queue<Action> mSyncHandlers = new Queue<Action>();

    public Action beginLoop()
    {
        if (mThread != null)
            return null;

        mThread = new Thread(run);
        mThread.Start();

        return onSyncUpdate;
    }

    public void endLoop()
    {
        if (mThread == null)
            return;

        mThread.Abort();
        mThread = null;

        mAsyncHandlers.Clear();
        mSyncHandlers.Clear();
    }

    public void runAsync(Action callabck)
    {
        mAsyncHandlers.Enqueue(callabck);
    }

    public void runSync(Action callback)
    {
        mSyncHandlers.Enqueue(callback);
    }

    private void run()
    {
        while (true)
        {
            Thread.Sleep(16);
            onAsyncUpdate();
        }
    }

    private void onAsyncUpdate()
    {
        if (mAsyncHandlers.Count > 0)
        {
            mAsyncHandlers.Dequeue()();
        }
    }

    private void onSyncUpdate()
    {
        if (mSyncHandlers.Count > 0)
        {
            mSyncHandlers.Dequeue()();
        }
    }
}
